package com.jichangxiu.dynamic.test.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.Properties;

/**
 * 初始化数据源
 *
 * @author Jcx
 * @date 2022/11/27 7:40
 */
@Component
public class JavaDataSourceProvider implements ApplicationListener<ContextRefreshedEvent> {

    private String[] configs = new String[]{"bootstrap.properties", "bootstrap.yml", "application.properties", "application.yml"};

    @Autowired
    private DataSourceInfoServiceImpl dataSourceInfoService;

    // 初始化本平台的数据源
    @PostConstruct
    public void init() throws Exception {
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("db/druid.yml"));
        DynamicDataSourceService.addDataSource(DynamicDataSource.DEFAULT_DB_KEY, properties);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configs[0]);
        if (ObjectUtil.isEmpty(inputStream)) {
            inputStream = this.getClass().getClassLoader().getResourceAsStream(configs[1]);
            if (ObjectUtil.isEmpty(inputStream)) {
                inputStream = this.getClass().getClassLoader().getResourceAsStream(configs[2]);
                if (ObjectUtil.isEmpty(inputStream)) {
                    inputStream = this.getClass().getClassLoader().getResourceAsStream(configs[3]);
                }
            }
        }
        if (ObjectUtil.isNotEmpty(inputStream)) {
            Properties pro = new Properties();
            pro.load(inputStream);
            DynamicDataSourceService.addDataSource(StrUtil.isEmpty(pro.getProperty("name")) ? IdUtil.randomUUID() : pro.getProperty("name"), pro);
        }
    }

    // 查询本平台数据库中，配置的游戏数据库的连接信息，并加载到 Map<Object, Object> dataSources = new HashMap<>()中
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            dataSourceInfoService.buildDynamicDataSourceFromDB();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

